import { IMAGE_MAX_WIDTH } from "../config";

export const file2base64 = (file: File) => {
    return new Promise<string>((resolve, rejects) => {
        const reader = new FileReader();
        reader.onload = ({ target }) => {
            if (!target) {
                console.log("file2base64 no target")
                return rejects();
            }
            if (!target.result) {
                console.log("file2base64 no result")
                return rejects();
            }
            resolve(target.result.toString());
        }
        reader.readAsDataURL(file);
    })
}

export const file2canvas = (file: File) => {
    return new Promise<HTMLCanvasElement>((resolve, rejects) => {
        file2base64(file).then((base64) => {
            const img = new Image();
            img.src = base64;
            img.onload = () => {
                const canvas = document.createElement("canvas");
                const car = canvas.getContext("2d");
                canvas.width = img.width > IMAGE_MAX_WIDTH ? IMAGE_MAX_WIDTH : img.width;
                canvas.height = (canvas.width / img.width) * img.height;
                car?.drawImage(img, 0, 0, canvas.width, canvas.height);
                resolve(canvas);
            }
        }).catch(rejects)
    })
}